from flask import Flask, jsonify, request
import jmcomic
import os
import threading
from datetime import datetime
# 注册插件
from plugins.MyImg2PdfPlugin import MyImg2PdfPlugin
from plugins.MyPDFMergerPlugin import MyPDFMergerPlugin

app = Flask(__name__)

# 创建配置对象
option = jmcomic.create_option_by_file('configs/option.yml')

# 存储下载任务状态
download_tasks = {}

class DownloadTask:
    def __init__(self, book_id):
        self.book_id = book_id
        self.status = "pending"  # pending, downloading, completed, failed
        self.start_time = None
        self.end_time = None
        self.error = None
        self.album_info = None
        self.download_path = None
        self.progress = {
            "total_chapters": 0,
            "completed_chapters": 0
        }

def download_worker(book_id):
    task = download_tasks[book_id]
    task.start_time = datetime.now()
    task.status = "downloading"
    
    try:
        # 开始下载
        album_detail, downloader = jmcomic.download_album(book_id, option)
        
        # 更新任务信息
        task.status = "completed"
        task.album_info = serialize_album_detail(album_detail)
        task.download_path = os.path.join(option.dir_rule.base_dir, str(book_id))
        
    except Exception as e:
        task.status = "failed"
        task.error = str(e)
    finally:
        task.end_time = datetime.now()

def serialize_album_detail(album):
    """将 JmAlbumDetail 对象转换为可序列化的字典"""
    return {
        'id': album.id if hasattr(album, 'id') else None,
        'name': album.name if hasattr(album, 'name') else None,
        'author': album.author if hasattr(album, 'author') else None,
        'description': album.description if hasattr(album, 'description') else None,
        'tags': album.tags if hasattr(album, 'tags') else [],
        'photo_list': [
            {
                'id': photo.id,
                'title': photo.title,
                'series_id': photo.series_id
            } for photo in (album.photo_list if hasattr(album, 'photo_list') else [])
        ]
    }

def serialize_downloader(downloader):
    """将 JmDownloader 对象转换为可序列化的字典"""
    return {
        'download_dir': downloader.download_dir if hasattr(downloader, 'download_dir') else None,
        'option': {
            'base_dir': downloader.option.dir_rule.base_dir if hasattr(downloader, 'option') else None,
        }
    }

@app.route('/download/<int:book_id>', methods=['GET'])
def start_download(book_id):
    if book_id in download_tasks:
        task = download_tasks[book_id]
        if task.status in ["pending", "downloading"]:
            return jsonify({
                'status': 'error',
                'message': f'漫画 ID: {book_id} 已经在下载队列中'
            }), 400
    
    # 创建新的下载任务
    download_tasks[book_id] = DownloadTask(book_id)
    
    # 启动下载线程
    thread = threading.Thread(target=download_worker, args=(book_id,))
    thread.start()
    
    return jsonify({
        'status': 'success',
        'message': f'开始下载漫画 ID: {book_id}',
        'data': {'book_id': book_id}
    })

@app.route('/status/<int:book_id>', methods=['GET'])
def check_status(book_id):
    if book_id not in download_tasks:
        return jsonify({
            'status': 'error',
            'message': f'找不到漫画 ID: {book_id} 的下载记录'
        }), 404
    
    task = download_tasks[book_id]
    
    response = {
        'status': task.status,
        'book_id': task.book_id,
        'start_time': task.start_time.isoformat() if task.start_time else None,
        'end_time': task.end_time.isoformat() if task.end_time else None,
        'progress': task.progress
    }
    
    if task.error:
        response['error'] = task.error
    if task.album_info:
        response['album_info'] = task.album_info
    if task.download_path:
        response['download_path'] = task.download_path
        
    return jsonify(response)

@app.route('/list', methods=['GET'])
def list_tasks():
    tasks = {}
    for book_id, task in download_tasks.items():
        tasks[book_id] = {
            'status': task.status,
            'start_time': task.start_time.isoformat() if task.start_time else None,
            'end_time': task.end_time.isoformat() if task.end_time else None
        }
    
    return jsonify({
        'status': 'success',
        'data': tasks
    })

@app.route('/status', methods=['GET'])
def status():
    return jsonify({
        'status': 'running',
        'base_dir': os.path.abspath(option.dir_rule.base_dir)
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000) 